package com.baihan.angus.app.game.busshow.ui.script_library.online_exhibition.room;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Display;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatImageButton;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.baihan.angus.app.game.basic.base.BaseResponse;
import com.baihan.angus.app.game.basic.utils.ComUtil;
import com.baihan.angus.app.game.basic.utils.Loog;
import com.baihan.angus.app.game.basic.utils.Tooast;
import com.baihan.angus.app.game.basic.utils.net.RetrofitHelper;
import com.baihan.angus.app.game.busshow.R;
import com.baihan.angus.app.game.busshow.adps.AudienceListAdapter;
import com.baihan.angus.app.game.busshow.adps.GameSeatAdp;
import com.baihan.angus.app.game.busshow.adps.MsgListAdapter;
import com.baihan.angus.app.game.busshow.adps.VoiceRoomSeatAdp;
import com.baihan.angus.app.game.busshow.pop_dialog.BgStoryDialog;
import com.baihan.angus.app.game.busshow.pop_dialog.InputTextMsgDialog;
import com.baihan.angus.app.game.busshow.pop_dialog.ScriptIntroDialog;
import com.baihan.angus.app.game.busshow.ui.script_library.online_exhibition.script_library.ScriptLibraryActivity;
import com.baihan.angus.app.game.busshow.views.SpaceItemDecoration;
import com.baihan.angus.app.game.common.bean.response.AudienceEntity;
import com.baihan.angus.app.game.common.bean.response.MemberEntity;
import com.baihan.angus.app.game.common.bean.response.MsgEntity;
import com.baihan.angus.app.game.common.bean.response.RoomDetailResponse;
import com.baihan.angus.app.game.common.bean.response.ScriptResponse;
import com.baihan.angus.app.game.common.bean.response.ScriptRole;
import com.baihan.angus.app.game.common.bean.response.Userinfo;
import com.baihan.angus.app.game.common.configs.UserConfig;
import com.baihan.angus.app.game.common.data_center.remote.api.RoomServer;
import com.baihan.angus.app.game.common.model.TRTCVoiceRoom;
import com.baihan.angus.app.game.common.model.TRTCVoiceRoomCallback;
import com.baihan.angus.app.game.common.model.TRTCVoiceRoomDef;
import com.baihan.angus.app.game.common.model.TRTCVoiceRoomDelegate;
import com.baihan.angus.app.game.common.util.ImageLoader;
import com.blankj.utilcode.constant.PermissionConstants;
import com.blankj.utilcode.util.PermissionUtils;
import com.blankj.utilcode.util.ScreenUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.gyf.immersionbar.ImmersionBar;
import com.tencent.liteav.audio.TXAudioEffectManager;
import com.tencent.trtc.TRTCCloudDef;
import com.trello.rxlifecycle2.android.ActivityEvent;
import com.trello.rxlifecycle2.components.support.RxAppCompatActivity;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

import static com.baihan.angus.app.game.common.model.TRTCVoiceRoomDef.SeatInfo.STATUS_CLOSE;
import static com.baihan.angus.app.game.common.model.TRTCVoiceRoomDef.SeatInfo.STATUS_UNUSED;
import static com.baihan.angus.app.game.common.model.TRTCVoiceRoomDef.SeatInfo.STATUS_USED;

/**
 * 语音聊天室基类
 */

public class VoiceRoomBaseActivity extends RxAppCompatActivity implements TRTCVoiceRoomDelegate, MsgListAdapter.OnItemClickListener,
        InputTextMsgDialog.OnTextSendListener, VoiceRoomSeatAdp.OnItemClickListener,
        VoiceRoomSeatAdp.OnPopupItemClickListener, GameSeatAdp.OnItemClickListener {

    protected static final int MAX_SEAT_SIZE = 9;
    protected static final String VOICEROOM_ROOM_ID = "room_id";
    protected static final String VOICEROOM_ROOM_NAME = "room_name";
    protected static final String VOICEROOM_USER_NAME = "user_name";
    protected static final String VOICEROOM_USER_ID = "user_id";
    protected static final String VOICEROOM_USER_SIG = "user_sig";
    protected static final String VOICEROOM_NEED_REQUEST = "need_request";
    protected static final String VOICEROOM_SEAT_COUNT = "seat_count";
    protected static final String VOICEROOM_AUDIO_QUALITY = "audio_quality";
    protected static final String VOICEROOM_USER_AVATAR = "user_avatar";
    protected static final String VOICEROOM_ROOM_COVER = "room_cover";
    protected static final String ROOM_DETAIL = "room_detail";

    private static final int CHANGE_SCRIPT = 0xb11;

    private static final int MESSAGE_USERNAME_COLOR_ARR[] = {
            R.color.trtcvoiceroom_color_msg_1,
            R.color.trtcvoiceroom_color_msg_2,
            R.color.trtcvoiceroom_color_msg_3,
            R.color.trtcvoiceroom_color_msg_4,
            R.color.trtcvoiceroom_color_msg_5,
            R.color.trtcvoiceroom_color_msg_6,
            R.color.trtcvoiceroom_color_msg_7,
    };

    protected String mSelfUserId;     //进房用户ID
    protected int mCurrentRole;    //用户当前角色
    protected Set<String> mSeatUserSet; //在座位上的主播集合
    protected TRTCVoiceRoom mTRTCVoiceRoom;
    private boolean isInitSeat;
    protected boolean mIsPlayEnd = false;//bgm播放完毕

    protected List<ScriptRole> mVoiceRoomSeatEntityList;
    protected Map<String, Boolean> mSeatUserMuteMap;
    protected VoiceRoomSeatAdp mVoiceRoomSeatAdp;
    protected GameSeatAdp mGameSeatAdp;
    protected AudienceListAdapter mAudienceListAdapter;
    protected RelativeLayout title;
    protected View statusBarFillView;
    protected FrameLayout root;
    protected LinearLayout llGame, llRoom, llDMTab, llPlayeTab, llSetting, llGameDmVoice, llScriptIntro;
    protected ImageView ivBack, ivDMAvatar, ivDMAvatar1, ivDmVoice, ivGameDmVoice, ivManagerTalk, ivGameManagerTalk, ivRootBg,
            ivScript, ivClue, ivProps, ivNote, ivMap, ivTeamUp, ivDeduction, ivDmMenu, ivRoleScript, ivRecord, ivSceneRender, ivMVP;
    protected AppCompatImageButton ibMicro, ibVolume, ibVoice, ibDmVoice, ibGameVolume;
    protected TextView tvRoomName, tvRoomType, tvRoomReverse, tvRoomId, tvInvite, tvWaitingNum, tvReady,
            tvDMName, tvRole, tvChangeScript, tvScriptName;
    protected Button btnSaySome;
    protected RecyclerView rvSeat, rvImMsg, rvAudience, rvImMsg1, rvSeat1;

    protected TXAudioEffectManager mAudioEffectManager;
    protected InputTextMsgDialog mInputTextMsgDialog;
    protected String mRoomId;
    protected RoomDetailResponse.Data mRoomDetail;
    protected String mRoomName;
    protected String mUserName;
    protected String mUserAvatar;
    protected int mSeatCount;
    protected String mRoomCover;
    protected String mMainSeatUserId;
    protected boolean mNeedRequest;
    protected int mAudioQuality;
    protected List<MsgEntity> mMsgEntityList;
    protected LinkedList<AudienceEntity> mAudienceEntityList;
    protected MsgListAdapter mMsgListAdapter;
    protected List<MemberEntity> mMemberEntityList;
    protected Map<String, MemberEntity> mMemberEntityMap;
    protected ScriptResponse.DataX.Data scriptResponse;
    protected TXAudioEffectManager.AudioMusicParam audioMusicParam;
    protected int bgmId = -1;
    protected String bgmUrl;

    private int mMessageColorIndex;
    private Context mContext;
    private boolean mIsMainSeatMute;
    private int mSelfSeatIndex = -1;
    private BgStoryDialog mBgStoryDialog;
    private ScriptIntroDialog mScriptIntroDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        UserConfig.getUserConfig().getUser().userType = Userinfo.UserType.VOICE_ROOM;
        mContext = this;
        // 应用运行时，保持不锁屏、全屏化
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_voice_room_base);
        initStatusBar();
        initView();
        initData();
        initListener();
    }

    protected void initView() {
        //Room
        root = (FrameLayout) findViewById(R.id.root);
        llRoom = (LinearLayout) findViewById(R.id.llRoom);
        llGame = (LinearLayout) findViewById(R.id.llGame);
        title = (RelativeLayout) findViewById(R.id.title);
        statusBarFillView = (View) findViewById(R.id.statusBarFillView);
        rvSeat = (RecyclerView) findViewById(R.id.rvSeat);
        rvImMsg = (RecyclerView) findViewById(R.id.rvImMsg);
        rvAudience = (RecyclerView) findViewById(R.id.rvAudience);
        ivBack = (ImageView) findViewById(R.id.ivBack);
        ibVolume = (AppCompatImageButton) findViewById(R.id.ibVolume);
        ivManagerTalk = (ImageView) findViewById(R.id.ivManagerTalk);
        ivDMAvatar = (ImageView) findViewById(R.id.ivDMAvatar);
        ivDMAvatar1 = (ImageView) findViewById(R.id.ivDMAvatar1);
        ivDmVoice = (ImageView) findViewById(R.id.ivDmVoice);
        ibMicro = (AppCompatImageButton) findViewById(R.id.ibMicro);
        ibVoice = (AppCompatImageButton) findViewById(R.id.ibVoice);
        ibDmVoice = (AppCompatImageButton) findViewById(R.id.ibDmVoice);
        tvRoomName = (TextView) findViewById(R.id.tvRoomName);
        tvRoomType = (TextView) findViewById(R.id.tvRoomType);
        tvRoomReverse = (TextView) findViewById(R.id.tvRoomReverse);
        tvRoomId = (TextView) findViewById(R.id.tvRoomId);
        tvInvite = (TextView) findViewById(R.id.tvInvite);
        tvWaitingNum = (TextView) findViewById(R.id.tvWaitingNum);
        tvReady = (TextView) findViewById(R.id.tvReady);
        tvDMName = (TextView) findViewById(R.id.tvDMName);
        tvRole = (TextView) findViewById(R.id.tvRole);
        tvChangeScript = (TextView) findViewById(R.id.tvChangeScript);
        btnSaySome = (Button) findViewById(R.id.btnSaySome);

        //Game
        llDMTab = (LinearLayout) findViewById(R.id.llDMTab);
        llPlayeTab = (LinearLayout) findViewById(R.id.llPlayeTab);
        rvImMsg1 = (RecyclerView) findViewById(R.id.rvImMsg1);
        rvSeat1 = (RecyclerView) findViewById(R.id.rvSeat1);
        ibGameVolume = (AppCompatImageButton) findViewById(R.id.ibGameVolume);
        llGameDmVoice = (LinearLayout) findViewById(R.id.llGameDmVoice);
        llSetting = (LinearLayout) findViewById(R.id.llSetting);
        llScriptIntro = (LinearLayout) findViewById(R.id.llScriptIntro);
        ivGameDmVoice = (ImageView) findViewById(R.id.ivGameDmVoice);
        ivGameManagerTalk = (ImageView) findViewById(R.id.ivGameManagerTalk);
        tvScriptName = (TextView) findViewById(R.id.tvScriptName);
        ivRootBg = (ImageView) findViewById(R.id.ivRootBg);
        ivScript = (ImageView) findViewById(R.id.ivScript);
        ivClue = (ImageView) findViewById(R.id.ivClue);
        ivProps = (ImageView) findViewById(R.id.ivProps);
        ivNote = (ImageView) findViewById(R.id.ivNote);
        ivMap = (ImageView) findViewById(R.id.ivMap);
        ivTeamUp = (ImageView) findViewById(R.id.ivTeamUp);
        ivDeduction = (ImageView) findViewById(R.id.ivDeduction);
        ivDmMenu = (ImageView) findViewById(R.id.ivDmMenu);
        ivRoleScript = (ImageView) findViewById(R.id.ivRoleScript);
        ivRecord = (ImageView) findViewById(R.id.ivRecord);
        ivSceneRender = (ImageView) findViewById(R.id.ivSceneRender);
        ivMVP = (ImageView) findViewById(R.id.ivMVP);

        LinearLayout.LayoutParams llTitle = (LinearLayout.LayoutParams) title.getLayoutParams();
        llTitle.topMargin = ImmersionBar.getStatusBarHeight(this);
        title.setLayoutParams(llTitle);

        RelativeLayout.LayoutParams rlGameTop = (RelativeLayout.LayoutParams) statusBarFillView.getLayoutParams();
        rlGameTop.topMargin = ImmersionBar.getStatusBarHeight(this);
        statusBarFillView.setLayoutParams(rlGameTop);

//        mViewSelectMember = new SelectMemberView(this);
        mInputTextMsgDialog = new InputTextMsgDialog(this);
        mInputTextMsgDialog.setmOnTextSendListener(this);
        mMsgEntityList = new ArrayList<>();
        mMemberEntityList = new ArrayList<>();
        mMemberEntityMap = new HashMap<>();

        ivBack.setOnClickListener(view -> {
            onBackPressed();
        });

        mSeatUserMuteMap = new HashMap<>();

        mMsgListAdapter = new MsgListAdapter(this, mMsgEntityList, this);
        rvImMsg.setLayoutManager(new LinearLayoutManager(this));
        rvImMsg.setAdapter(mMsgListAdapter);

        rvImMsg1.setLayoutManager(new LinearLayoutManager(this));
        rvImMsg1.setAdapter(mMsgListAdapter);

        mAudienceEntityList = new LinkedList<>();
        mAudienceListAdapter = new AudienceListAdapter(this, mAudienceEntityList);
        LinearLayoutManager lm = new LinearLayoutManager(this);
        lm.setOrientation(LinearLayoutManager.HORIZONTAL);
        rvAudience.setLayoutManager(lm);
        rvAudience.setAdapter(mAudienceListAdapter);

        //设置座位间距
        int screenWidth = ScreenUtils.getScreenWidth() - ComUtil.Dp2Px(this, 16) * 2;// 16  recycleView 左右缩进距离
        int totalSpace = (screenWidth - ComUtil.Dp2Px(this, 120) * 2);// 120 item宽度
        SpaceItemDecoration decoration = new SpaceItemDecoration(totalSpace, this, 2);
        rvSeat.addItemDecoration(decoration);

        int screenWidth1 = ScreenUtils.getScreenWidth() - ComUtil.Dp2Px(this, 16) * 2;// 16  recycleView 左右缩进距离
        int totalSpace1 = (screenWidth1 - ComUtil.Dp2Px(this, 85) * 2);// 85 item宽度
        SpaceItemDecoration decoration1 = new SpaceItemDecoration(totalSpace1, this, 2);
        rvSeat1.addItemDecoration(decoration1);

    }

    protected void initData() {
        Intent intent = getIntent();
        mRoomId = intent.getStringExtra(VOICEROOM_ROOM_ID);
        mRoomDetail = (RoomDetailResponse.Data) intent.getSerializableExtra(ROOM_DETAIL);
        mRoomName = intent.getStringExtra(VOICEROOM_ROOM_NAME);
//        mUserName = intent.getStringExtra(VOICEROOM_USER_NAME);
        mSelfUserId = intent.getStringExtra(VOICEROOM_USER_ID);
        mNeedRequest = intent.getBooleanExtra(VOICEROOM_NEED_REQUEST, false);
//        mUserAvatar = intent.getStringExtra(VOICEROOM_USER_AVATAR);
        mRoomCover = intent.getStringExtra(VOICEROOM_ROOM_COVER);
        mAudioQuality = intent.getIntExtra(VOICEROOM_AUDIO_QUALITY, TRTCCloudDef.TRTC_AUDIO_QUALITY_DEFAULT);
        mSeatCount = intent.getIntExtra(VOICEROOM_SEAT_COUNT, 0);
        mUserName = UserConfig.getUserConfig().getUser().getNickname();
        mUserAvatar = UserConfig.getUserConfig().getUser().getAvatar();
        mTRTCVoiceRoom = TRTCVoiceRoom.sharedInstance(this);
        mTRTCVoiceRoom.setDelegate(this);

        initRoomData(mRoomDetail);
    }

    public void initRoomData(RoomDetailResponse.Data roomData) {
        mVoiceRoomSeatEntityList = new ArrayList<>();
        mVoiceRoomSeatEntityList.clear();
        for (int i = 1; i < roomData.getScript_role().size() + 1; i++) {
            ScriptRole scriptRole = roomData.getScript_role().get(i - 1);
            scriptRole.index = i;
        }

        mVoiceRoomSeatEntityList.addAll(roomData.getScript_role());

        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 2);
        mVoiceRoomSeatAdp = new VoiceRoomSeatAdp(this, mVoiceRoomSeatEntityList, roomData.getUser().getId(), this, this);
        rvSeat.setLayoutManager(gridLayoutManager);
        rvSeat.setAdapter(mVoiceRoomSeatAdp);

        GridLayoutManager gridLayoutManager1 = new GridLayoutManager(this, 2);
        mGameSeatAdp = new GameSeatAdp(this, mVoiceRoomSeatEntityList, roomData.getUser().getId(), this);
        rvSeat1.setLayoutManager(gridLayoutManager1);
        rvSeat1.setAdapter(mGameSeatAdp);

        //等待区
        tvWaitingNum.setText(mAudienceEntityList.size() + "人");

        Glide.with(this).asBitmap().load(roomData.getScript().getPoster()).into(new SimpleTarget<Bitmap>() {
            @Override
            public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                Drawable drawable = new BitmapDrawable(resource);
                root.setBackground(drawable);
            }
        });

        if (UserConfig.getUserConfig().getUser().getUser_id().equals(roomData.getUser().getId())) {
            tvChangeScript.setVisibility(View.GONE);
        } else {
            tvChangeScript.setVisibility(View.GONE);
        }
        tvChangeScript.setOnClickListener(view -> {
            Intent intent = new Intent();
            intent.setClass(this, ScriptLibraryActivity.class);
            startActivityForResult(intent, CHANGE_SCRIPT);
        });

        if (!UserConfig.getUserConfig().getUser().getUser_id().equals(roomData.getUser().getId())) {//普通玩家
            tvReady.setText(getString(R.string.ready));
        } else {//DM
            tvReady.setText(getString(R.string.start));
        }

        if (roomData.getType() == 0) {
            tvRoomType.setText(getString(R.string.waitingRoom));
        } else if (roomData.getType() == 1) {
            tvRoomType.setText(getString(R.string.appointRoom));
        }

        if (roomData.getReverse() == 0) {
            tvRoomReverse.setText(getString(R.string.notAllowReserse));
        } else if (roomData.getReverse() == 1) {
            tvRoomReverse.setText(getString(R.string.allowReserse));
        }

        tvScriptName.setText(roomData.getScript().getName());

        llScriptIntro.setOnClickListener(v -> {
            if (null == mScriptIntroDialog) {
                mScriptIntroDialog = new ScriptIntroDialog(this);
            }
            mScriptIntroDialog.initData(roomData);
            mScriptIntroDialog.show();
        });

        mAudioEffectManager = mTRTCVoiceRoom.getAudioEffectManager();
    }

    private void initStatusBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
    }

    //麦克风开关
    private void updateMicButton() {
        if (checkButtonPermission()) {
            boolean currentMode = !ibMicro.isSelected();
            if (currentMode) {
                if (!isSeatMute(mSelfSeatIndex)) {
                    updateMuteStatusView(mSelfUserId, false);
                    mTRTCVoiceRoom.muteLocalAudio(false);
                    Tooast.normalInfo(getString(R.string.trtcvoiceroom_toast_you_have_turned_on_the_microphone));
                } else {
                    Tooast.normalInfo(getString(R.string.trtcvoiceroom_seat_already_mute));
                }
            } else {
                mTRTCVoiceRoom.muteLocalAudio(true);
                updateMuteStatusView(mSelfUserId, true);
                Tooast.normalInfo(getString(R.string.trtcvoiceroom_toast_you_have_turned_off_the_microphone));
            }
        }
    }

    //游戏中麦克风开关
    private void updateGameMicButton() {
        if (checkButtonPermission()) {
            boolean currentMode = !ibVoice.isSelected();
            if (currentMode) {
                if (!isSeatMute(mSelfSeatIndex)) {
                    updateMuteStatusView(mSelfUserId, false);
                    mTRTCVoiceRoom.muteLocalAudio(false);
                    Tooast.normalInfo(getString(R.string.trtcvoiceroom_toast_you_have_turned_on_the_microphone));
                } else {
                    Tooast.normalInfo(getString(R.string.trtcvoiceroom_seat_already_mute));
                }
            } else {
                mTRTCVoiceRoom.muteLocalAudio(true);
                updateMuteStatusView(mSelfUserId, true);
                Tooast.normalInfo(getString(R.string.trtcvoiceroom_toast_you_have_turned_off_the_microphone));
            }
        }
    }

    private void updateDmMicButton() {
        if (checkButtonPermission()) {
            boolean currentMode = !ibDmVoice.isSelected();
            if (currentMode) {
                if (!isSeatMute(mSelfSeatIndex)) {
                    updateMuteStatusView(mSelfUserId, false);
                    mTRTCVoiceRoom.muteLocalAudio(false);
                    Tooast.normalInfo(getString(R.string.trtcvoiceroom_toast_you_have_turned_on_the_microphone));
                } else {
                    Tooast.normalInfo(getString(R.string.trtcvoiceroom_seat_already_mute));
                }
            } else {
                mTRTCVoiceRoom.muteLocalAudio(true);
                updateMuteStatusView(mSelfUserId, true);
                Tooast.normalInfo(getString(R.string.trtcvoiceroom_toast_you_have_turned_off_the_microphone));
            }
        }
    }

    //静音开关
    private void updateBGVolume() {
        boolean currentMode = !ibVolume.isSelected();
        if (currentMode) {
            updateBGVolume(false);
            updateGameBGVolume(false);
            mTRTCVoiceRoom.muteAllRemoteAudio(false);
            Tooast.normalInfo("已关闭静音");
        } else {
            mTRTCVoiceRoom.muteAllRemoteAudio(true);
            updateBGVolume(true);
            updateGameBGVolume(true);
            Tooast.normalInfo(getString(R.string.already_mute));
        }
    }

    //游戏中静音开关
    private void updateGameBGVolume() {
        boolean currentMode = !ibGameVolume.isSelected();
        if (currentMode) {
            updateBGVolume(false);
            updateGameBGVolume(false);
            mTRTCVoiceRoom.muteAllRemoteAudio(false);
//            mAudioEffectManager.resumePlayMusic(bgmId);
            Tooast.normalInfo("已关闭静音");
        } else {
            mTRTCVoiceRoom.muteAllRemoteAudio(true);
            updateBGVolume(true);
            updateGameBGVolume(true);
            Tooast.normalInfo(getString(R.string.already_mute));
//            mAudioEffectManager.pausePlayMusic(bgmId);
        }
    }

    private boolean isSeatMute(int seatIndex) {
        ScriptRole scriptRole = findSeatEntityFromUserId(seatIndex);
        if (scriptRole != null) {
            return scriptRole.isSeatMute;
        }
        return false;
    }

    protected void initListener() {
        ibMicro.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PermissionUtils.permission(PermissionConstants.MICROPHONE).callback(new PermissionUtils.FullCallback() {
                    @Override
                    public void onGranted(List<String> permissionsGranted) {
                        updateMicButton();
                    }

                    @Override
                    public void onDenied(List<String> permissionsDeniedForever, List<String> permissionsDenied) {
                        Tooast.normalInfo(getString(R.string.trtcvoiceroom_tips_open_audio));
                    }
                }).request();
            }
        });

        ibVolume.setOnClickListener(view -> {
            updateBGVolume();
        });

        ibGameVolume.setOnClickListener(view -> {
            updateGameBGVolume();
        });

        ibVoice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PermissionUtils.permission(PermissionConstants.MICROPHONE).callback(new PermissionUtils.FullCallback() {
                    @Override
                    public void onGranted(List<String> permissionsGranted) {
                        updateGameMicButton();
                    }

                    @Override
                    public void onDenied(List<String> permissionsDeniedForever, List<String> permissionsDenied) {
                        Tooast.normalInfo(getString(R.string.trtcvoiceroom_tips_open_audio));
                    }
                }).request();
            }
        });

        ibDmVoice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PermissionUtils.permission(PermissionConstants.MICROPHONE).callback(new PermissionUtils.FullCallback() {
                    @Override
                    public void onGranted(List<String> permissionsGranted) {
                        updateDmMicButton();
                    }

                    @Override
                    public void onDenied(List<String> permissionsDeniedForever, List<String> permissionsDenied) {
                        Tooast.normalInfo(getString(R.string.trtcvoiceroom_tips_open_audio));
                    }
                }).request();
            }
        });
        btnSaySome.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showInputMsgDialog();
            }
        });
    }

    /**
     * 判断是否为主播，有操作按钮的权限
     *
     * @return 是否有权限
     */
    protected boolean checkButtonPermission() {
        boolean hasPermission = (mCurrentRole == TRTCCloudDef.TRTCRoleAnchor);
        if (!hasPermission) {
            Tooast.normalInfo("没有权限");
        }
        return hasPermission;
    }

    /**
     * 发消息弹出框
     */
    private void showInputMsgDialog() {
        WindowManager windowManager = getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        WindowManager.LayoutParams lp = mInputTextMsgDialog.getWindow().getAttributes();
        lp.width = display.getWidth(); //设置宽度
        mInputTextMsgDialog.getWindow().setAttributes(lp);
        mInputTextMsgDialog.setCancelable(true);
        mInputTextMsgDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
        mInputTextMsgDialog.show();
    }

    @Override
    public void onTextSend(String msg) {
        if (msg.length() == 0) {
            return;
        }
        byte[] byte_num = msg.getBytes(StandardCharsets.UTF_8);
        if (byte_num.length > 160) {
            Toast.makeText(this, getString(R.string.please_enter_content), Toast.LENGTH_SHORT).show();
            return;
        }

        //消息回显
        MsgEntity entity = new MsgEntity();
        entity.userName = getString(R.string.me);
        entity.content = msg;
        entity.isChat = true;
        entity.userId = mSelfUserId;
        entity.type = MsgEntity.TYPE_NORMAL;
        showImMsg(entity);

        mTRTCVoiceRoom.sendRoomTextMsg(msg, new TRTCVoiceRoomCallback.ActionCallback() {
            @Override
            public void onCallback(int code, String msg) {
                if (code == 0) {
                    Tooast.normalInfo(getString(R.string.alreadySend));
                } else {
                    Tooast.normalInfo(getString(R.string.sendFail));
                }
            }
        });
    }

    public void resetSeatView() {
        mSeatUserSet.clear();
        for (ScriptRole entity : mVoiceRoomSeatEntityList) {
            entity.isUsed = false;
        }
        mVoiceRoomSeatAdp.notifyDataSetChanged();
        mGameSeatAdp.notifyDataSetChanged();
    }

    @Override
    public void onError(int code, String message) {

    }

    @Override
    public void onWarning(int code, String message) {

    }

    @Override
    public void onDebugLog(String message) {

    }

    @Override
    public void onRoomDestroy(String roomId) {

    }

    @Override
    public void onRoomInfoChange(TRTCVoiceRoomDef.RoomInfo roomInfo) {
        mNeedRequest = roomInfo.needRequest;
        mRoomName = roomInfo.roomName;
        mRoomId = roomInfo.roomId;
        mSeatCount = roomInfo.seatCount;
        tvRoomName.setText(roomInfo.roomName);
        tvRoomId.setText("ID:" + roomInfo.roomId);
        String roomCover = roomInfo.coverUrl;
//        ImageLoader.loadImage(this, mRootBg, roomCover, R.drawable.trtcvoiceroom_ic_cover);
    }

    @Override
    public void onSeatListChange(final List<TRTCVoiceRoomDef.SeatInfo> seatInfoList) {
        //先刷一遍界面
        final List<String> userids = new ArrayList<>();
        for (int i = 0; i < seatInfoList.size(); i++) {
            TRTCVoiceRoomDef.SeatInfo newSeatInfo = seatInfoList.get(i);
            // 底层返回的第一个座位是主播哦！特殊处理一下
            if (i == 0) {
                if (mMainSeatUserId == null || !mMainSeatUserId.equals(newSeatInfo.userId)) {
                    //主播上线啦
                    mMainSeatUserId = newSeatInfo.userId;
                    userids.add(newSeatInfo.userId);
//                    tvDMName.setText(getString(R.string.trtcvoiceroom_tv_information_acquisition));
                }
                continue;
            }
            // 接下来是座位区域的列表
            ScriptRole oldSeatEntity = mVoiceRoomSeatEntityList.get(i - 1);
            if (newSeatInfo.userId != null && !newSeatInfo.userId.equals(oldSeatEntity.userId)) {
                //userId相同，可以不用重新获取信息了
                //但是如果有新的userId进来，那么应该去拿一下主播的详细信息
                userids.add(newSeatInfo.userId);
            }
            oldSeatEntity.userId = newSeatInfo.userId;
            // 座位的状态更新一下
            switch (newSeatInfo.status) {
                case STATUS_UNUSED:
                    oldSeatEntity.isUsed = false;
                    oldSeatEntity.isClose = false;
                    break;
                case STATUS_CLOSE:
                    oldSeatEntity.isUsed = false;
                    oldSeatEntity.isClose = true;
                    break;
                case STATUS_USED:
                    oldSeatEntity.isUsed = true;
                    oldSeatEntity.isClose = false;
                    break;
                default:
                    break;
            }
            oldSeatEntity.isSeatMute = newSeatInfo.mute;
        }
        for (String userId : userids) {
            if (!mSeatUserMuteMap.containsKey(userId)) {
                mSeatUserMuteMap.put(userId, true);
            }
        }
        mVoiceRoomSeatAdp.notifyDataSetChanged();
        mGameSeatAdp.notifyDataSetChanged();
        //所有的userId拿到手，开始去搜索详细信息了
        mTRTCVoiceRoom.getUserInfoList(userids, new TRTCVoiceRoomCallback.UserListCallback() {
            @Override
            public void onCallback(int code, String msg, List<TRTCVoiceRoomDef.UserInfo> list) {
                // 解析所有人的userinfo
                Map<String, TRTCVoiceRoomDef.UserInfo> map = new HashMap<>();
                for (TRTCVoiceRoomDef.UserInfo userInfo : list) {
                    map.put(userInfo.userId, userInfo);
                }
                for (int i = 0; i < seatInfoList.size(); i++) {
                    TRTCVoiceRoomDef.SeatInfo newSeatInfo = seatInfoList.get(i);
                    TRTCVoiceRoomDef.UserInfo userInfo = map.get(newSeatInfo.userId);
                    if (userInfo == null) {
                        continue;
                    }
                    boolean isUserMute = mSeatUserMuteMap.get(userInfo.userId);
                    // 底层返回的第一个座位是房主哦！特殊处理一下
                    if (i == 0) {
                        if (newSeatInfo.status == STATUS_USED) {
                            //主播上线啦
                            ImageLoader.loadImage(mContext, ivDMAvatar, userInfo.userAvatar, R.mipmap.ic_test_bg);
                            ImageLoader.loadImage(mContext, ivDMAvatar1, userInfo.userAvatar, R.mipmap.ic_test_bg);
                            if (TextUtils.isEmpty(userInfo.userName)) {
//                                tvDMName.setText(userInfo.userId);
                            } else {
//                                tvDMName.setText(userInfo.userName);
                            }
                            updateMuteStatusView(userInfo.userId, isUserMute);
                        } else {
                            tvDMName.setText(getString(R.string.trtcvoiceroom_tv_the_dm_is_not_online));
                        }
                    } else {
                        // 接下来是座位区域的列表
                        ScriptRole seatEntity = mVoiceRoomSeatEntityList.get(i - 1);
                        if (userInfo.userId.equals(seatEntity.userId)) {
//                            seatEntity.name = userInfo.userName;
//                            seatEntity.avatar = userInfo.userAvatar;
                            seatEntity.isUserMute = isUserMute;
                        }
                    }
                }
                mVoiceRoomSeatAdp.notifyDataSetChanged();
                mGameSeatAdp.notifyDataSetChanged();
                if (!isInitSeat) {
                    getAudienceList();
                    isInitSeat = true;
                }
            }
        });
    }

    @Override
    public void onAnchorEnterSeat(int index, TRTCVoiceRoomDef.UserInfo user) {
        if (index != 0) {
            // 房主上麦就别提醒了
            Loog.d("VoiceRoomBaseActivity", "onAnchorEnterSeat userInfo:" + user);
            MsgEntity msgEntity = new MsgEntity();
            msgEntity.type = MsgEntity.TYPE_NORMAL;
            msgEntity.userName = user.userName;
            msgEntity.content = getString(R.string.hasChoosed) + mRoomDetail.getScript_role().get(index - 1).getName();
            showImMsg(msgEntity);
            mAudienceListAdapter.removeMember(user.userId);
            tvWaitingNum.setText(mAudienceListAdapter.getItemCount() + "人");
            Loog.dTag("EnterSeat", "count = " + mAudienceListAdapter.getItemCount());
            if (user.userId.equals(mSelfUserId)) {
                mSelfSeatIndex = index;
            }
        }
    }

    @Override
    public void onAnchorLeaveSeat(int index, TRTCVoiceRoomDef.UserInfo user) {
        if (index != 0) {
            // 房主上麦就别提醒了
            Loog.d("VoiceRoomBaseActivity", "onAnchorLeaveSeat userInfo:" + user);
            MsgEntity msgEntity = new MsgEntity();
            msgEntity.type = MsgEntity.TYPE_NORMAL;
            msgEntity.userName = user.userName;
//            showImMsg(msgEntity);
            AudienceEntity entity = new AudienceEntity();
            entity.audienceId = user.userId;
            entity.audienceAvatar = user.userAvatar;
            mAudienceListAdapter.addMember(entity);
            tvWaitingNum.setText(mAudienceListAdapter.getItemCount() + "人");
            if (user.userId.equals(mSelfUserId)) {
                mSelfSeatIndex = -1;
            }
        }
    }

    @Override
    public void onSeatMute(int index, boolean isMute) {
        MsgEntity msgEntity = new MsgEntity();
        msgEntity.type = MsgEntity.TYPE_NORMAL;
        if (isMute) {
            msgEntity.content = getString(R.string.trtcvoiceroom_tv_the_position_has_muted, index);
        } else {
            msgEntity.content = getString(R.string.trtcvoiceroom_tv_the_position_has_unmuted, index);
        }
        showImMsg(msgEntity);
        ScriptRole seatEntity = findSeatEntityFromUserId(index);
        if (seatEntity == null) {
            return;
        }
        if (index == mSelfSeatIndex) {
            if (isMute) {
                mTRTCVoiceRoom.muteLocalAudio(true);
                updateMuteStatusView(mSelfUserId, true);
            } else if (!seatEntity.isUserMute) {
                mTRTCVoiceRoom.muteLocalAudio(false);
                updateMuteStatusView(mSelfUserId, false);
            }
        }
    }

    @Override
    public void onSeatClose(int index, boolean isClose) {
        MsgEntity msgEntity = new MsgEntity();
        msgEntity.type = MsgEntity.TYPE_NORMAL;
        msgEntity.content = isClose ? getString(R.string.trtcvoiceroom_tv_the_owner_ban_this_position, index) :
                getString(R.string.trtcvoiceroom_tv_the_owner_not_ban_this_position, index);
        showImMsg(msgEntity);
    }


    @Override
    public void onUserMicrophoneMute(String userId, boolean mute) {
        Loog.d("VoiceRoomBaseActivity", "onUserMicrophoneMute userId:" + userId + " mute:" + mute);
        mSeatUserMuteMap.put(userId, mute);
        updateMuteStatusView(userId, mute);
    }

    private void updateMuteStatusView(String userId, boolean mute) {
        if (userId == null) {
            return;
        }
        if (userId.equals(mMainSeatUserId)) {
            ivDmVoice.setVisibility(mute ? View.VISIBLE : View.GONE);
//            ivGameDmVoice.setVisibility(mute ? View.VISIBLE : View.GONE);
            ivGameDmVoice.setImageResource(mute ? R.mipmap.ic_user_voice_off : R.mipmap.ic_user_voice_on);
            if (mute) {
                ivManagerTalk.setVisibility(View.GONE);
                ivGameManagerTalk.setVisibility(View.INVISIBLE);
            } else {
                ivGameManagerTalk.setVisibility(View.VISIBLE);
            }
            mIsMainSeatMute = mute;
        } else {
            ScriptRole seatEntity = findSeatEntityFromUserId(userId);
            if (seatEntity != null) {
                if (!seatEntity.isSeatMute && mute != seatEntity.isUserMute) {
                    seatEntity.isUserMute = mute;
                    mVoiceRoomSeatAdp.notifyDataSetChanged();
                    mGameSeatAdp.notifyDataSetChanged();
                }
            }
        }
        if (userId.equals(mSelfUserId)) {
            ibMicro.setSelected(!mute);
            ibVoice.setSelected(!mute);
            ibDmVoice.setSelected(!mute);
        }
    }

    private void updateBGVolume(boolean mute) {
        ibVolume.setSelected(!mute);
    }

    public void updateGameBGVolume(boolean mute) {
        ibGameVolume.setSelected(!mute);
    }

    private ScriptRole findSeatEntityFromUserId(String userId) {
        if (mVoiceRoomSeatEntityList != null) {
            for (ScriptRole seatEntity : mVoiceRoomSeatEntityList) {
                if (userId.equals(seatEntity.userId)) {
                    return seatEntity;
                }
            }
        }
        return null;
    }

    private ScriptRole findSeatEntityFromUserId(int index) {
        if (index == -1) {
            return null;
        }
        if (mVoiceRoomSeatEntityList != null) {
            for (ScriptRole scriptRole : mVoiceRoomSeatEntityList) {
                if (index == scriptRole.index) {
                    return scriptRole;
                }
            }
        }
        return null;
    }

    @Override
    public void onAudienceEnter(TRTCVoiceRoomDef.UserInfo userInfo) {
        Loog.dTag("onAudienceEnter userInfo:", userInfo);
        MsgEntity msgEntity = new MsgEntity();
        msgEntity.type = MsgEntity.TYPE_NORMAL;
        msgEntity.content = getString(R.string.trtcvoiceroom_tv_enter_room, "");
        msgEntity.userName = userInfo.userName;
        showImMsg(msgEntity);
        if (userInfo.userId.equals(mSelfUserId)) {
            return;
        }
        AudienceEntity entity = new AudienceEntity();
        entity.audienceId = userInfo.userId;
        entity.audienceAvatar = userInfo.userAvatar;
        mAudienceListAdapter.addMember(entity);
        tvWaitingNum.setText(mAudienceListAdapter.getItemCount() + "人");
    }

    @Override
    public void onAudienceExit(TRTCVoiceRoomDef.UserInfo userInfo) {
        Loog.d("VoiceRoomBaseActivity", "onAudienceExit userInfo:" + userInfo);
        MsgEntity msgEntity = new MsgEntity();
        msgEntity.type = MsgEntity.TYPE_NORMAL;
        msgEntity.userName = userInfo.userName;
        msgEntity.content = getString(R.string.trtcvoiceroom_tv_exit_room, "");
        showImMsg(msgEntity);
        mAudienceListAdapter.removeMember(userInfo.userId);
        tvWaitingNum.setText(mAudienceListAdapter.getItemCount() + "人");
    }

    @Override
    public void onUserVolumeUpdate(List<TRTCCloudDef.TRTCVolumeInfo> userVolumes, int totalVolume) {
        for (TRTCCloudDef.TRTCVolumeInfo info : userVolumes) {
            if (info != null) {
                int volume = info.volume;
                if (info.userId.equals(mMainSeatUserId)) {
                    ivManagerTalk.setVisibility(mIsMainSeatMute ? View.GONE : volume > 20 ? View.VISIBLE : View.GONE);
                    ivGameManagerTalk.setVisibility(mIsMainSeatMute ? View.INVISIBLE : volume > 20 ? View.VISIBLE : View.INVISIBLE);
                } else {
                    ScriptRole entity = findSeatEntityFromUserId(info.userId);
                    if (entity != null) {
                        entity.isTalk = volume > 20 ? true : false;
                        mVoiceRoomSeatAdp.notifyDataSetChanged();
                        mGameSeatAdp.notifyDataSetChanged();
                    }
                }
            }
        }
    }

    @Override
    public void onRecvRoomTextMsg(String message, TRTCVoiceRoomDef.UserInfo userInfo) {
        MsgEntity msgEntity = new MsgEntity();
        msgEntity.userId = userInfo.userId;
        msgEntity.userName = userInfo.userName;
        msgEntity.content = message;
        msgEntity.type = MsgEntity.TYPE_NORMAL;
        msgEntity.isChat = true;
        showImMsg(msgEntity);
    }

    @Override
    public void onRecvRoomCustomMsg(String cmd, String message, TRTCVoiceRoomDef.UserInfo userInfo) {

    }

    @Override
    public void onReceiveNewInvitation(String id, String inviter, String cmd, String content) {

    }

    @Override
    public void onInviteeAccepted(String id, String invitee) {

    }

    @Override
    public void onInviteeRejected(String id, String invitee) {

    }

    @Override
    public void onInvitationCancelled(String id, String invitee) {

    }

    @Override
    public void onAgreeClick(int position) {

    }

    //获取游客列表
    protected void getAudienceList() {
        mTRTCVoiceRoom.getUserInfoList(null, new TRTCVoiceRoomCallback.UserListCallback() {
            @Override
            public void onCallback(int code, String msg, List<TRTCVoiceRoomDef.UserInfo> list) {
                if (code == 0) {
                    Loog.d("VoiceRoomBaseActivity", "getAudienceList list size:" + list.size());
                    for (TRTCVoiceRoomDef.UserInfo userInfo : list) {
                        Loog.d("VoiceRoomBaseActivity", "getAudienceList userInfo:" + userInfo);
                        if (!mSeatUserMuteMap.containsKey(userInfo.userId)) {
                            AudienceEntity audienceEntity = new AudienceEntity();
                            audienceEntity.audienceAvatar = userInfo.userAvatar;
                            audienceEntity.audienceId = userInfo.userId;
                            mAudienceListAdapter.addMember(audienceEntity);
                        }
                        if (userInfo.userId.equals(mSelfUserId)) {
                            continue;
                        }
                        MemberEntity memberEntity = new MemberEntity();
                        memberEntity.userId = userInfo.userId;
                        memberEntity.userAvatar = userInfo.userAvatar;
                        memberEntity.userName = userInfo.userName;
                        memberEntity.type = MemberEntity.TYPE_IDEL;
                        if (!mMemberEntityMap.containsKey(memberEntity.userId)) {
                            mMemberEntityMap.put(memberEntity.userId, memberEntity);
                            mMemberEntityList.add(memberEntity);
                        }
                    }
                }
            }
        });
    }

    protected int changeSeatIndexToModelIndex(int srcSeatIndex) {
        return srcSeatIndex + 1;
    }

    protected void showImMsg(final MsgEntity entity) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (mMsgEntityList.size() > 1000) {
                    while (mMsgEntityList.size() > 900) {
                        mMsgEntityList.remove(0);
                    }
                }
                if (!TextUtils.isEmpty(entity.userName)) {
                    if (mMessageColorIndex >= MESSAGE_USERNAME_COLOR_ARR.length) {
                        mMessageColorIndex = 0;
                    }
                    int color = MESSAGE_USERNAME_COLOR_ARR[mMessageColorIndex];
                    entity.color = getResources().getColor(color);
                    mMessageColorIndex++;
                }
                mMsgEntityList.add(entity);
                mMsgListAdapter.notifyDataSetChanged();
                rvImMsg.smoothScrollToPosition(mMsgListAdapter.getItemCount());
                rvImMsg1.smoothScrollToPosition(mMsgListAdapter.getItemCount());
            }
        });
    }

    @Override
    public void onUserPoster(int position) {
        ScriptRole scriptRole = mVoiceRoomSeatEntityList.get(position);
        Glide.with(this).asBitmap().load(scriptRole.getPoster()).into(new SimpleTarget<Bitmap>() {
            @Override
            public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                Drawable drawable = new BitmapDrawable(resource);
                root.setBackground(drawable);
            }
        });
    }

    @Override
    public void onScriptPoster(int position) {
        Glide.with(this).asBitmap().load(mRoomDetail.getScript().getPoster()).into(new SimpleTarget<Bitmap>() {
            @Override
            public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                Drawable drawable = new BitmapDrawable(resource);
                root.setBackground(drawable);
            }
        });
    }

    @Override
    public void onBgStory(int position) {
        ScriptRole scriptRole = mVoiceRoomSeatEntityList.get(position);
        String bgStory = scriptRole.getBack_story_text();
        if (null == mBgStoryDialog) {
            mBgStoryDialog = new BgStoryDialog(this);
        }
        mBgStoryDialog.initData(bgStory);
        mBgStoryDialog.setCanceledOnTouchOutside(false);
        mBgStoryDialog.show();
    }

    //加入游戏
    @Override
    public void onJoin(int position) {

    }

    //禁言
    @Override
    public void onVoice(int position) {

    }

    //更换剧本
    @SuppressLint("CheckResult")
    public void updateScript() {
        RetrofitHelper.createApi(RoomServer.class).updateRoom(mRoomId, scriptResponse.getScript_id())
                .compose(this.bindUntilEvent(ActivityEvent.DESTROY))
                .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<BaseResponse>() {
                    @Override
                    public void accept(BaseResponse baseResponse) throws Exception {
                        if (baseResponse.getCode() == 1) {
                            updateRoomInfo();
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        Tooast.normalInfo(throwable.getMessage());
                    }
                });
    }

    //更新房间信息
    @SuppressLint("CheckResult")
    public void updateRoomInfo() {
        RetrofitHelper.createApi(RoomServer.class).updateRoomDetail(mRoomId)
                .compose(this.bindUntilEvent(ActivityEvent.DESTROY))
                .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<RoomDetailResponse>() {
                    @Override
                    public void accept(RoomDetailResponse roomDetailResponse) throws Exception {
                        if (roomDetailResponse.getCode() == 1) {
                            initRoomData(roomDetailResponse.getData());
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        Tooast.normalInfo(throwable.getMessage());
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CHANGE_SCRIPT) {
            if (resultCode == RESULT_OK) {
                scriptResponse = (ScriptResponse.DataX.Data) data.getSerializableExtra("scriptItem");
                updateScript();
            }
        }
    }

    //游戏中点击头像事件
    @Override
    public void onItemClick(int position) {

    }

    //禁言
    @Override
    public void onVoiceMute(int position) {

    }

    @Override
    public void onChat(int position) {

    }
}